package com.xx.zmq;

import org.zeromq.SocketType;
import org.zeromq.ZAuth;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Xander
 * @version 1.0
 * @ClassName: ZmqClient
 * @Description:
 * @Date: 2023/9/26
 * @since JDK 1.8
 */

public class ZmqServer {

    public static ZMQ.Socket publisher;

    static {
        ZContext   context = new ZContext();
        ZAuth zAuth = new ZAuth(context);
        File tempFile = null;
        try {

            tempFile = File.createTempFile("passwords", ".txt");
            tempFile.deleteOnExit(); // 确保JVM退出时删除临时文件
            InputStream in = ZmqServer.class.getResourceAsStream("/passwords.txt");
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String tempFilePath = tempFile.getAbsolutePath();
        System.out.println(tempFilePath);
        zAuth.configurePlain("*", tempFilePath);

        publisher = context.createSocket(SocketType.PUB);
        publisher.setPlainServer(true);
        publisher.bind("tcp://*:8089");
    }

    public static void sendData(String topic ,byte[] msg) {
        publisher.sendMore(topic);
        publisher.send(msg);
    }

}
